# {
#             "regionExtKey": "446623465822814216",
#             "pointExtKey": "446623465822814218",
#             "pointCode": "pointA1",
#             "pointName": "测试门点A1",
#             "isUsed": true,
#             "isUseKq": false,
#             "dataSysCode": 100,
#             "remarks": "",
#             "isDeleted": false,
#             "deleteTime": null,
#             "modifyTime": "2023-03-28 13:32:36.0",
#             "inOutFlag": 0,
#             "sysModifyTime": "2023-03-28 17:35:58.68"
#         }

from module.huada.entity.base_entity import BaseEntity
from plugin import MSsqlClient, Config, Mylogger, MyTime


class DoorsEntity(BaseEntity):
    url = "tunion/get/doors"
    table_name = "doors"
    api_data_list = []
    create_table = True
    get_time = "2000-01-01 00:00:00"
    order_by = "sysModifyTime"
    sync_list = []
    write_back_dict = {}
    update_cache_time = '2021-01-01 00:00:00'

    def __init__(self, **kwargs) -> None:
        self.regionExtKey = kwargs.get('regionExtKey')  # 区域主键
        self.pointExtKey = kwargs.get('pointExtKey')  # 门点主键
        self.pointCode = kwargs.get('pointCode')  # 门点编码
        self.pointName = kwargs.get('pointName')  # 门点名称
        self.isUsed = kwargs.get('isUsed')  # 是否启用
        self.isUseKq = kwargs.get('isUseKq')  # 是否考勤
        self.dataSysCode = kwargs.get('dataSysCode')  # 数据系统编码
        self.remarks = kwargs.get('remarks')  # 备注
        self.isDeleted = kwargs.get('isDeleted')  # 是否删除
        self.deleteTime = kwargs.get('deleteTime')  # 删除时间
        self.modifyTime = kwargs.get('modifyTime')  # 修改时间
        self.inOutFlag = kwargs.get('inOutFlag')  # 进出标志
        self.sysModifyTime = kwargs.get('sysModifyTime')  # 系统修改时间
        self.isdeal = kwargs.get('isdeal') or 0  # 是否处理过，0未处理，1已处理, -n 代表第n次处理失败
        self.id = kwargs.get('id') or 0

    @classmethod
    def do_sync(cls, client: MSsqlClient, objs: list[BaseEntity]):
        # 每天更新一次缓存
        if MyTime.timestamp()- int(MyTime.timestampfrom(cls.update_cache_time)) > 24*60*60:
            cls.update_cache_time = MyTime.timestr()
            init_node_cache()
            init_node_group_cache()


        result_num = [0, 0]  # 写，删
        for obj in objs:
            group_key = obj.regionExtKey
            door_addr = get_addr(obj.pointCode)
            if door_addr is None:
                write_back(cls.write_back_dict, -99, obj)
                continue
            if not get_node_cache(door_addr):
                write_back(cls.write_back_dict, -99, obj)
                continue
            get_node_group_cache(group_key)
            result = 0
            if obj.isDeleted == 'True':
                result = 1  # 删除只做一次
                if node_cache.__contains__(door_addr) and node_group_cache.__contains__(group_key):
                    result = client.delete(f"""
                    delete from acscon_groupmember where gid = '{node_group_cache[group_key]}' and uid = '{node_cache[door_addr]}'
                    """)
                    result_num[1] += result
                else:
                    Mylogger.info(f"删除失败，未找到门点 {door_addr} 或区域 {group_key} ")
            else:
                if not node_group_cache.__contains__(group_key) or node_group_cache[group_key] == '':
                    Mylogger.info(f"新增/修改失败，未找到区域 {group_key}")
                elif node_cache.__contains__(door_addr):
                    # result = client.execute(f"""
                    # if exists (select 1 from acscon_groupmember with(nolock) where uid = '{node_cache[door_addr]}')
                    # begin
                    #     update acscon_groupmember set gid = '{node_group_cache[group_key]}' where uid = '{node_cache[door_addr]}'
                    # end
                    # else
                    # begin
                    #     insert into acscon_groupmember (gid,uid) values ('{node_group_cache[group_key]}','{node_cache[door_addr]}')
                    # end
                    # """)
                    # result_num[0] += result
                    # 区域门点不做同步了
                    result_num[0] += 1
                else:
                    Mylogger.info(f'门点 {node_cache[door_addr]} 不存在')

            write_back(cls.write_back_dict, result, obj)

        Mylogger.info(f"doors同步完成，写入{result_num[0]}条，删除{result_num[1]}条")
        return super().do_sync(client, objs)


def write_back(dic, result, obj):
    if result is not None:
        # 同步成功，key = 1 ,否则isdeal 减一
        key = 1 if result == 1 else (int(obj.isdeal) - 1)
        if result == -99:
            key = -99
        if not dic.__contains__(str(key)):
            dic[str(key)] = []

        dic[str(key)].append(str(obj.id))


def get_addr(pointcode):
    # pointcode去掉前面的systemcode+ '-'后，按每三位分割
    # 例如 2001-001001001491，去掉2001-后，按每三位分割，得到001,001,001,491
    try:
        _addr = pointcode.split('-')[1]
        if len(_addr) != 12:
            Mylogger.error(f"门点编码{pointcode}格式错误")
            return None
        addr = f"{int(_addr[0:3])}-{int(_addr[3:6])}#{int(_addr[6:9])}-{int(_addr[9:12])}"
        return addr
    except Exception as e:
        Mylogger.error(f"门点编码{pointcode}格式错误")
        return None

node_group_cache = {}


def get_node_group_cache(group_key):
    if not node_group_cache.__contains__(group_key):
        node_group_cache[group_key] = ""

    if node_group_cache[group_key] == "":
        client = MSsqlClient(charset='cp936', **Config.module_config.huada.client_link)
        results = client.select_to_dict(f"select id from acscon_group where type = 10 and [desc] = '{group_key}'")
        if len(results) > 0:
            node_group_cache[group_key] = results[0]['id']


def get_node_cache(node_key):
    # if not node_cache.__contains__(node_key):
    #     node_cache[node_key] = ""

    if not node_cache.__contains__(node_key):
        client = MSsqlClient(charset='cp936', **Config.module_config.huada.client_link)
        results = client.select_to_dict(f"select id from acscon_realnode where addr = '{node_key}'")
        if len(results) > 0:
            node_cache[node_key] = results[0]['id']
    
    result = True if node_cache.__contains__(node_key) else False
    if not result:
        Mylogger.error(f'门点 {node_key} 在安冠系统中不存在')
    return result


node_cache = {}


def init_node_cache():
    client = MSsqlClient(charset='cp936', **Config.module_config.huada.client_link)
    results = client.select_to_dict("""
    select a.id,a.addr
    from   acscon_realnode a
    inner join
        acscon_iotype   b
    on     a.iotypeid = b.id
    where  b.descr like '%{}%'
    """.format('dr'))
    if len(results) > 0:
        for result in results:
            node_cache[result['addr']] = result['id']
        Mylogger.info(f"门点缓存初始化完成，共{len(results)}条")
    


def init_node_group_cache():
    client = MSsqlClient(charset='cp936', **Config.module_config.huada.client_link)
    results = client.select_to_dict("select id,[desc] from acscon_group where type = 10")
    if len(results) > 0:
        for result in results:
            node_group_cache[result['desc']] = result['id']
        Mylogger.info(f"区域缓存初始化完成，共{len(results)}条")


# init_node_cache()
# init_node_group_cache()
